﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Krile.Kernel.Control;
using Krile.Kernel.Data;
using Krile.Kernel;
using Krile.Kernel.Control.Surface;

namespace Wassrile.Controls
{
    public class Pictogram : MessageObject
    {
        public string code;

        public Image _cache;
        public Image cache
        {
            get { return _cache; }
            set
            {
                if (animate != null)
                {
                    ImageAnimator.StopAnimate(_cache, animate);
                    animate = null;
                }
                _cache = value;
                if (ImageAnimator.CanAnimate(_cache))
                {
                    animate = new EventHandler(FrameUpdated);
                    ImageAnimator.Animate(_cache, animate);
                }
            }
        }
        EventHandler animate = null;
        private void FrameUpdated(object sender, EventArgs e)
        {
            if (activated && ParentForm != null)
            {
                ParentForm.RefreshTL(false);
            }
        }

        public Pictogram(string cod)
            : base()
        {
            code = cod;
        }

        public override void Draw(Graphics g, CompositeDescriptor desc)
        {
            if (animate != null)
                ImageAnimator.UpdateFrames(_cache);
            int xp = desc.StartXPos + desc.LeftTop.X;
            int h = desc.LeftTop.Y;
            int c = 0;
            if (desc.Heights.Length > 1)
            {
                xp = desc.LeftTop.X;
                h = desc.Heights[0] + desc.LeftTop.Y;
                c++;
            }
            int yp = (int)Math.Ceiling((desc.Heights[c] - 16) / 2.0);
            if (cache != null)
                g.DrawImage(cache, new Rectangle(xp, h + yp, 16, 16));
            else
                g.DrawRectangle(Pens.Red, new Rectangle(xp, h + yp, 16, 16));
        }

        public override bool HitTest(Point position)
        { return false; }

        public override void Composite(Compositor compz)
        {
            compz.SetCurrentLineHeight(16);
            if (compz.ClientWidth - compz.CurrentXPosition < 16)
                compz.MoveNewLine();
            compz.CurrentXPosition += 16;
        }

        volatile bool activated = false;
        public override void Activate()
        {
            activated = true;
            cache = Core.PictogramResolver.GetPictogram(code).Clone() as Image;
        }

        public override void Release()
        {
            if (cache != null)
                cache.Dispose();
            cache = null;
            activated = false;
        }
    }
}
